import { defineComponent, ExtractPropTypes, PropType } from 'vue'
import { Option } from '../_util/normalizeOptions'
import List from '../virtual-list'

export const optionListProps = {
  prefixCls: String,
  options: Array as PropType<Option[]>,
  values: Set,
  virtualScroll: Boolean
}

export type OptionListProps = ExtractPropTypes<typeof optionListProps>

export default defineComponent({
  name: 'x-option-list',
  props: optionListProps,
  slots: ['label'],
  emits: ['click', 'select'],
  setup(props, { emit, slots }) {
    const { prefixCls } = props
    const optionPrefixCls = `${prefixCls}-option`

    function onClick(option) {
      emit('click', option)
      emit('select', option)
    }

    const genItem = (...args) => {
      const { item: option, index } = args[0]
      let label = slots.default?.(...args) ?? option.label
      if (slots.label) label = slots.label({ option, index })

      const selected = props.values.has(option.value)

      const clazz = [
        optionPrefixCls,
        {
          selected,
          [`${optionPrefixCls}-selected`]: selected,
          [`${optionPrefixCls}-disabled`]: option.disabled
        }
      ]

      return (
        <div class={clazz} onClick={() => onClick(option)} {...option}>
          <div class={`${optionPrefixCls}-content`}>{label}</div>
        </div>
      )
    }

    return () => {
      const slots = { default: genItem }

      return <List virtual={props.virtualScroll} items={props.options} itemKey='value' v-slots={slots} />
    }
  }
})
